package me.cxlr.qinlauncher2.view.settings;

import android.os.Bundle;

import androidx.appcompat.app.AlertDialog;
import androidx.preference.DropDownPreference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.SwitchPreferenceCompat;

import java.util.ArrayList;
import java.util.List;

import me.cxlr.qinlauncher2.R;
import me.cxlr.qinlauncher2.constants.Constants;
import me.cxlr.qinlauncher2.constants.LauncherAction;
import me.cxlr.qinlauncher2.dao.ActionDao;
import me.cxlr.qinlauncher2.dao.AppDao;
import me.cxlr.qinlauncher2.dao.KeyActionDao;
import me.cxlr.qinlauncher2.manager.SoftwareManager;
import me.cxlr.qinlauncher2.model.Action;
import me.cxlr.qinlauncher2.model.App;
import me.cxlr.qinlauncher2.model.AppAndAction;
import me.cxlr.qinlauncher2.model.KeyAction;
import me.cxlr.qinlauncher2.util.ResourceUtil;
import me.cxlr.qinlauncher2.util.SharedPreferencesUtil;
import me.cxlr.qinlauncher2.util.ThemeUtil;

/**
 * @author 酷安用户:山轮纸
 */
public class NumberKeyLongSettingsFragment extends PreferenceFragmentCompat {

    SwitchPreferenceCompat useNumberKey;

    private AppDao appDao;
    private ActionDao actionDao;
    private KeyActionDao keyActionDao;

    private DropDownPreference ddpKeyNumberKey0;
    private DropDownPreference ddpKeyNumberKey1;
    private DropDownPreference ddpKeyNumberKey2;
    private DropDownPreference ddpKeyNumberKey3;
    private DropDownPreference ddpKeyNumberKey4;
    private DropDownPreference ddpKeyNumberKey5;
    private DropDownPreference ddpKeyNumberKey6;
    private DropDownPreference ddpKeyNumberKey7;
    private DropDownPreference ddpKeyNumberKey8;
    private DropDownPreference ddpKeyNumberKey9;
    private DropDownPreference ddpKeyNumberKeyStar;
    private DropDownPreference ddpKeyNumberKeyPound;

    private boolean useNumberKeyFlag;

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.preferences_number_key_long_settings, rootKey);

        useNumberKey = findPreference("use_number_key_long");
        ddpKeyNumberKey0 = findPreference("number_key_long_0");
        ddpKeyNumberKey1 = findPreference("number_key_long_1");
        ddpKeyNumberKey2 = findPreference("number_key_long_2");
        ddpKeyNumberKey3 = findPreference("number_key_long_3");
        ddpKeyNumberKey4 = findPreference("number_key_long_4");
        ddpKeyNumberKey5 = findPreference("number_key_long_5");
        ddpKeyNumberKey6 = findPreference("number_key_long_6");
        ddpKeyNumberKey7 = findPreference("number_key_long_7");
        ddpKeyNumberKey8 = findPreference("number_key_long_8");
        ddpKeyNumberKey9 = findPreference("number_key_long_9");
        ddpKeyNumberKeyStar = findPreference("number_key_long_*");
        ddpKeyNumberKeyPound = findPreference("number_key_long_#");

        appDao = new AppDao();
        actionDao = new ActionDao();
        keyActionDao = new KeyActionDao();
        List<KeyAction> keyActionList = keyActionDao.findKeyActionListByKeyType(4);
        for (KeyAction keyAction : keyActionList) {
            switch (keyAction.getKeyName()) {
                case Constants.NUMBER_KEY_LONG_0:
                    initNumberKeySelectDropDownPreference(getString(R.string.number_key_long_0_title), ddpKeyNumberKey0, keyAction);
                    break;
                case Constants.NUMBER_KEY_LONG_1:
                    initNumberKeySelectDropDownPreference(getString(R.string.number_key_long_1_title), ddpKeyNumberKey1, keyAction);
                    break;
                case Constants.NUMBER_KEY_LONG_2:
                    initNumberKeySelectDropDownPreference(getString(R.string.number_key_long_2_title), ddpKeyNumberKey2, keyAction);
                    break;
                case Constants.NUMBER_KEY_LONG_3:
                    initNumberKeySelectDropDownPreference(getString(R.string.number_key_3_title), ddpKeyNumberKey3, keyAction);
                    break;
                case Constants.NUMBER_KEY_LONG_4:
                    initNumberKeySelectDropDownPreference(getString(R.string.number_key_4_title), ddpKeyNumberKey4, keyAction);
                    break;
                case Constants.NUMBER_KEY_LONG_5:
                    initNumberKeySelectDropDownPreference(getString(R.string.number_key_long_5_title), ddpKeyNumberKey5, keyAction);
                    break;
                case Constants.NUMBER_KEY_LONG_6:
                    initNumberKeySelectDropDownPreference(getString(R.string.number_key_long_6_title), ddpKeyNumberKey6, keyAction);
                    break;
                case Constants.NUMBER_KEY_LONG_7:
                    initNumberKeySelectDropDownPreference(getString(R.string.number_key_long_7_title), ddpKeyNumberKey7, keyAction);
                    break;
                case Constants.NUMBER_KEY_LONG_8:
                    initNumberKeySelectDropDownPreference(getString(R.string.number_key_long_8_title), ddpKeyNumberKey8, keyAction);
                    break;
                case Constants.NUMBER_KEY_LONG_9:
                    initNumberKeySelectDropDownPreference(getString(R.string.number_key_long_9_title), ddpKeyNumberKey9, keyAction);
                    break;
                case Constants.NUMBER_KEY_LONG_STAR:
                    initNumberKeySelectDropDownPreference(getString(R.string.number_key_long_star_title), ddpKeyNumberKeyStar, keyAction);
                    break;
                case Constants.NUMBER_KEY_LONG_POUND:
                    initNumberKeySelectDropDownPreference(getString(R.string.number_key_long_pound_title), ddpKeyNumberKeyPound, keyAction);
                    break;
                default:
                    break;
            }

        }

        useNumberKeyFlag = SharedPreferencesUtil.getInstance().getBoolean("use_number_key_long", false);
        setNumberKeySelectEnabled(useNumberKeyFlag);

        assert useNumberKey != null;
        useNumberKey.setOnPreferenceChangeListener((preference, newValue) -> {
            useNumberKeyFlag = Boolean.parseBoolean(newValue.toString());
            setNumberKeySelectEnabled(useNumberKeyFlag);
            return true;
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        ThemeUtil.initTheme();
    }

    /**
     * 设置选择数字键对应功能的按钮是否可点击
     *
     * @param useNumberKeyFlag 是否使用数字键功能
     */
    private void setNumberKeySelectEnabled(boolean useNumberKeyFlag) {
        if (useNumberKeyFlag) {
            ddpKeyNumberKey0.setEnabled(true);
            ddpKeyNumberKey1.setEnabled(true);
            ddpKeyNumberKey2.setEnabled(true);
            ddpKeyNumberKey3.setEnabled(true);
            ddpKeyNumberKey4.setEnabled(true);
            ddpKeyNumberKey5.setEnabled(true);
            ddpKeyNumberKey6.setEnabled(true);
            ddpKeyNumberKey7.setEnabled(true);
            ddpKeyNumberKey8.setEnabled(true);
            ddpKeyNumberKey9.setEnabled(true);
            ddpKeyNumberKeyStar.setEnabled(true);
            ddpKeyNumberKeyPound.setEnabled(true);
        } else {
            ddpKeyNumberKey0.setEnabled(false);
            ddpKeyNumberKey1.setEnabled(false);
            ddpKeyNumberKey2.setEnabled(false);
            ddpKeyNumberKey3.setEnabled(false);
            ddpKeyNumberKey4.setEnabled(false);
            ddpKeyNumberKey5.setEnabled(false);
            ddpKeyNumberKey6.setEnabled(false);
            ddpKeyNumberKey7.setEnabled(false);
            ddpKeyNumberKey8.setEnabled(false);
            ddpKeyNumberKey9.setEnabled(false);
            ddpKeyNumberKeyStar.setEnabled(false);
            ddpKeyNumberKeyPound.setEnabled(false);
        }
    }

    /**
     * init DropDownPreference
     *
     * @param title              数字按键名称，用作dialog的Title
     * @param dropDownPreference DropDownPreference
     * @param keyAction          KeyAction
     */
    private void initNumberKeySelectDropDownPreference(String title, DropDownPreference dropDownPreference, KeyAction keyAction) {
        switch (keyAction.getActionType()) {
            case 1:
                dropDownPreference.setSummary(getString(R.string.number_key_long_select_open_app_summary, keyAction.getApp().getLabel()));
                break;
            case 2:
                String label = ResourceUtil.getString(requireActivity(), keyAction.getAction().getResLabel());
                dropDownPreference.setSummary(getString(R.string.number_key_long_select_action_summary, label));
                break;
            case 0:
                dropDownPreference.setSummary(getString(R.string.number_key_no_select_summary));
                break;
            default:
                break;
        }
        dropDownPreference.setOnPreferenceClickListener(view -> {
            dialogChoice(keyAction, "选择" + title, keyAction.getKeyName(), dropDownPreference);
            return true;
        });
    }

    /**
     * 选择动作或应用
     *
     * @param title title
     */
    private void dialogChoice(KeyAction keyAction, String title, String keyName, DropDownPreference dropDownPreference) {
        ArrayList<AppAndAction> appAndActionList = new ArrayList<>(16);
        List<Action> actionList = actionDao.findAllAction();
        if (actionList != null) {
            for (Action entity : actionList) {
                String label = ResourceUtil.getString(requireActivity(), entity.getResLabel());
                if (entity.getActionName().equals(LauncherAction.NO.getAction())){
                    appAndActionList.add(AppAndAction.builder().id(entity.getId()).label(label).type(0).build());
                }else{
                    appAndActionList.add(AppAndAction.builder().id(entity.getId()).label(label).type(2).build());
                }
            }
        }
        List<App> appList = appDao.findAllApp();
        if (appList != null) {
            for (App entity : appList) {
                appAndActionList.add(AppAndAction.builder().id(entity.getId()).label(entity.getLabel()).type(1).build());
            }
        }

        String[] id = new String[appAndActionList.size()];
        String[] label = new String[appAndActionList.size()];
        int[] type = new int[appAndActionList.size()];
        for (int i = 0; i < appAndActionList.size(); i++) {
            id[i] = appAndActionList.get(i).getId();
            label[i] = appAndActionList.get(i).getLabel();
            type[i] = appAndActionList.get(i).getType();
        }

        AlertDialog alertDialog = new AlertDialog.Builder(requireContext())
                .setTitle(title)
                .setItems(label, (dialog, which) -> {
                    updateNumberKeyAction(keyAction, dropDownPreference, id[which], type[which]);
                    dialog.dismiss();
                })
                .setPositiveButton("关闭", (dialog, which) -> dialog.dismiss())
                .create();
        alertDialog.show();
    }

    /**
     * 修改数字键长按
     *
     * @param keyAction          数字键动作
     * @param dropDownPreference DropDownPreference
     * @param id                 被选中的主键
     * @param type               被选中的主键的类型
     */
    private void updateNumberKeyAction(KeyAction keyAction, DropDownPreference dropDownPreference, String id, int type) {
        if (type == Constants.KEY_ACTION_TYPE_OPEN_APP) {
            App app = appDao.findAppById(id);
            keyAction.setActionType(1);
            keyAction.setAction(null);
            keyAction.setApp(app);
        } else if (type == Constants.KEY_ACTION_TYPE_ACTION) {
            Action action = actionDao.findActionById(id);
            keyAction.setActionType(2);
            keyAction.setAction(action);
            keyAction.setApp(null);
        } else if (type == Constants.KEY_ACTION_TYPE_NO) {
            keyAction.setActionType(0);
            keyAction.setAction(null);
            keyAction.setApp(null);
        }
        keyActionDao.updateKeyAction(keyAction);
        switch (keyAction.getActionType()) {
            case 1:
                dropDownPreference.setSummary(getString(R.string.number_key_select_open_app_summary, keyAction.getApp().getLabel()));
                break;
            case 2:
                String label = ResourceUtil.getString(requireActivity(), keyAction.getAction().getResLabel());
                dropDownPreference.setSummary(getString(R.string.number_key_select_action_summary, label));
                break;
            case 0:
                dropDownPreference.setSummary(getString(R.string.number_key_no_select_summary));
                break;
            default:
                break;
        }
    }
}